package cn.edu.cxcyzx.controller;

import java.util.Calendar;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.cxcyzx.conf.Role;
import cn.edu.cxcyzx.entity.Admin;
import cn.edu.cxcyzx.entity.Student;
import cn.edu.cxcyzx.entity.Teacher;
import cn.edu.cxcyzx.service.AdminService;
import cn.edu.cxcyzx.service.StudentService;
import cn.edu.cxcyzx.service.TeacherService;
import cn.edu.cxcyzx.supervisor.ResultDo;
import cn.edu.cxcyzx.supervisor.ServiceFit;
import cn.edu.cxcyzx.util.MsgJSON;


@Controller
@RequestMapping("/")
public class LoginController {
	
	@Resource
	private ServiceFit serviceFit;
	
	@RequestMapping("index")
	public String loginView(){
		return "./login";
	}
	
	@RequestMapping("login")
	public ModelAndView login(HttpSession session,@RequestParam(value="username") String username,@RequestParam(value="userpwd") String userpwd){
		
		ModelAndView modelAndView=new ModelAndView("login");
		
		ResultDo<Object> resultDo=serviceFit.getUserService().login(username, userpwd);
		Role r=null;
		if(resultDo.isSuccess()){
			r=Role.getById(resultDo.getFalg());
			switch (resultDo.getFalg()) {
			case 2:
				Student stu=(Student)resultDo.getResult();
				session.setAttribute(r.getName(),stu);
				session.setAttribute("roleID",stu.getStuId());
				break;
			case 3:
				Teacher tea=(Teacher)resultDo.getResult();
				session.setAttribute(r.getName(),tea);
				session.setAttribute("roleID",tea.getTeaId());
				break;
			default:
				Admin admin=(Admin)resultDo.getResult();
				session.setAttribute(r.getName(),admin);
				session.setAttribute("roleID",admin.getAdminId());
				break;
			}
			return new ModelAndView("redirect:./"+r.getName()+"/home.do");
		}else{
			modelAndView.addObject("errorMsg", resultDo.getMessage());
			return modelAndView;
		}		
	}
	/**
	 * 修改登陆密码
	 * @param session
	 * @param pwd
	 * @return
	 */
	@RequestMapping("/update_pwd")
	@ResponseBody
	public MsgJSON update_pwd(HttpSession session,@RequestParam(value="pwd")String pwd){
		String account=(String) session.getAttribute("roleID");
		System.out.println("roleID:"+account);
		serviceFit.getUserService().updateSecret(account, pwd);
		return MsgJSON.success();
	}
}
